package com.mall.task.init;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdScheduler;

import com.mall.manager.service.ScheduleJobService;
import com.mall.untils.ScheduleJob;

@SuppressWarnings({"rawtypes","unchecked"})
public class JobInit {

	Logger logger = Logger.getLogger(JobInit.class);
	
	@Resource(name = "scheduler")
	private StdScheduler scheduler;
	
	@Resource
	private ScheduleJobService scheduleJobService;

	/**
	 * 初始化定时任务
	 * @throws Exception
	 */
	public void init() throws Exception {
		List<ScheduleJob> jobList = scheduleJobService.findScheduleJob();
		for (ScheduleJob job : jobList) {
			deleteJob(job);// 删除任务
			addJob(job);// 添加任务
		}
	}
	
	/**
	 * 删除一个job
	 * 
	 * @param scheduleJob
	 * @throws SchedulerException
	 */
	public void deleteJob(ScheduleJob scheduleJob) throws SchedulerException {

		logger.info(scheduler + "***删除任务****key***" + (scheduleJob.getJobName() + scheduleJob.getJobGroup()));
		JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
		scheduler.deleteJob(jobKey);

	}
	
	/**
	 * 添加任务
	 * 
	 * @param scheduleJob
	 * @throws SchedulerException
	 */
	public void addJob(ScheduleJob scheduleJob) throws SchedulerException {

		if (scheduleJob == null || !(scheduleJob.getJobStatus())) {
			return;
		}

		logger.info(scheduler + "***添加任务****key***" + (scheduleJob.getJobName() + scheduleJob.getJobGroup()));
		TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());

		CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

		// 不存在，创建一个
		if (null == trigger) {
			Class clazz = scheduleJob.getIsConcurrent() == true ? QuartzJobFactory.class : QuartzJobFactoryExecution.class;

			JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity(scheduleJob.getJobName(), scheduleJob.getJobGroup()).build();

			jobDetail.getJobDataMap().put("scheduleJob", scheduleJob);

			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression());

			trigger = TriggerBuilder.newTrigger().withIdentity(scheduleJob.getJobName(), scheduleJob.getJobGroup()).withSchedule(scheduleBuilder).build();

			scheduler.scheduleJob(jobDetail, trigger);
		} else {
			// Trigger已存在，那么更新相应的定时设置
			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression());

			// 按新的cronExpression表达式重新构建trigger
			trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

			// 按新的trigger重新设置job执行
			scheduler.rescheduleJob(triggerKey, trigger);
		}
	}
	
}
